package leetcode

import (
	"fmt"
	"strings"
)

// 解法一 位图
func lengthOfLongestSubstring(s string) int {
	result, left, right := 0, 0, 0
	var bitSet [256]bool // 初始化时都为false

	for left < len(s) {
		fmt.Println(string(s[right]), "    ", s[right], "     ", bitSet[s[right]])
		// 右侧字符对应的bitSet被标记true，说明此字符在X位置重复，需要左侧向前移动，直到将X标记为false
		if bitSet[s[right]] { // 变为true，证明有重复，从左开始到一直将重复的去掉
			bitSet[s[left]] = false
			left++
		} else { // 没有重复值
			bitSet[s[right]] = true
			right++
		}
		if result < right-left {
			result = right - left
		}
		if result+left >= len(s) || right >= len(s) {
			break
		}
	}
	return result

}

// 解法二 滑动窗口
func lengthOfLongestSubstring_(s string) int {
	if len(s) == 0 {
		return 0
	}
	var freq [256]int
	result, left, right := 0, 0, -1

	for left < len(s) {
		if right+1 < len(s) && freq[s[right+1]-'a'] == 0 {
			freq[s[right+1]-'a']++
			right++
		} else {
			freq[s[left]-'a']--
			left++
		}
		result = max(result, right-left+1)
	}
	return result
}

func max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func lengthOfLongestSubstring_Loss(s string) int {
	maxLength := 0
	//fmt.Println(len(s))
	if len(s) == 1 {
		maxLength = 1
	}
	for i := 0; i <= len(s); i++ {
		for j := 0; j <= len(s)-i; j++ {
			tmpStr := s[j : j+i]
			//fmt.Println(tmpStr)
			boo := false
			for k, v := range tmpStr {
				lastIndex := strings.LastIndex(tmpStr, string(v))
				if k == lastIndex {
					boo = true
				} else {
					boo = false
					break
				}
			}
			if boo {
				maxLength = len(tmpStr)
				break
			}
		}
	}

	return maxLength
}
